const app = getApp()
import {
    requestApi
} from '../../../api'
import {
    extend
} from '../../../sdk/extend'
const mobileReg = /^(13|15|16|17|18|14|19)[0-9]{9}$/
import md5 from '../../../utils/md5.min.js'
Page({
    data: {
        rotocolContent: [],
        countryArray: [],
        countryIndex: 0,
        isShowClear: false,
        mobilePhone: '',
        isShowCode: false,
        requestFlag: false,
        codeRequestFlag: false, // 获取验证码flag
        vCodeValue: '',
        isVFocus: true,
        timer: null,
        newUserReceivePrice: app.data.newUserPop && app.data.newUserPop.price || ''
    },
    onLoad() {
        this.getCountryCode()
        this.getProtocolContent()
    },
    getProtocolContent: function () {
        app.request({
            url: requestApi.getProtocolContentUrl,
            login: false,
            data: {
                protocol_name: 'login_account'
            },
        }, (data) => {
            this.setData({
                protocolContent: data.original.data
            })
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        })
    },
    // 跳转协议页面
    readPurchaseNotes: function (e) {
        let protocolName = e.currentTarget.dataset.protocol
        let url = `/pages/goods/purchaseNotes/purchaseNotes?protocol_name=${protocolName}`

        wx.navigateTo({
            url: url,
        })
    },
    pickerChange: function (e) {
        this.setData({
            countryIndex: e.detail.value
        })
    },
    getCountryCode: function () {
        // let url = API_URL
        let url = requestApi.countryCodeUrl
        let countryArray

        app.request({
            url: url,
            login: false,
            data: {},
        }, (data) => {
            countryArray = data.original.countrycodes

            this.setData({
                countryArray: countryArray
            })
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        })
    },
    getVcode: function (e) {
        if (this.data.authorizeBtn) {
            this.dialog.showDialog()
            return false
        }

        let {
            mobilePhone,
            countryArray,
            countryIndex
        } = this.data;
        let countryCode = countryArray[countryIndex].countrycode
        let send_timestamp = new Date().getTime();
        let send_sign = md5('4a68cd1c04adcbd49e599a38f6f82b5a' + send_timestamp + mobilePhone);
        let options = {
            url: requestApi.vCodeUrl,
            method: 'POST',
            data: {
                'send_sign': send_sign,
                'send_timestamp': send_timestamp,
                'receiver': mobilePhone,
                'country_code': countryCode,
                'service_type': '6',
                'receiver_type': '1'
            },
        }
        // 手机号验证
        if (!mobilePhone) {
            wx.showModal({
                showCancel: false,
                content: '请输入手机号码',
            })
            return false
        }
        // 正则验证手机号码验证
        if (!mobileReg.test(mobilePhone)) {
            wx.showModal({
                showCancel: false,
                content: '请输入正确手机号码'
            })
            return false
        }

        if (this.data.codeRequestFlag) return false
        app.request(
            options,
            (data) => {},
            (error) => {
                wx.showModal({
                    title: '提示',
                    showCancel: false,
                    content: error,
                })
            })

        clearInterval(this.data.timer);
        this.countDown();
        this.setData({
            isShowCode: true,
            vCodeValue: '',
            codeText: ''
        });

    },
    bindKeyInput(e) {
        let {
            isShowClear
        } = this.data;

        if (e.detail.value != '') {
            isShowClear = true;
        } else {
            isShowClear = false;
        }

        this.setData({
            mobilePhone: e.detail.value,
            isShowClear
        });
    },
    clearInput() {
        this.setData({
            mobilePhone: '',
            isShowClear: false
        });
    },
    codeBack() {
        this.setData({
            isShowCode: false,
            codeRequestFlag: false
        });
    },
    showVCode: function (e) {
        const that = this;

        that.setData({
            vCodeValue: e.detail.value,
        });

        if (e.detail.value.length == 6) {
            this.formSubmit()
        }
    },
    tapFn(e) {
        const that = this;
        that.setData({
            isVFocus: true,
        });
    },
    countDown: function () {
        let that = this
        let codeText = ''
        let time = 60

        that.setData({
            codeRequestFlag: true,
        })

        this.data.timer = setInterval(function () {
            time = time - 1;
            codeText = time + '秒后可重新发送验证码';
            if (time > 0) {
                that.setData({
                    codeText: codeText,
                })
            } else {
                clearInterval(that.data.timer)

                that.setData({
                    codeRequestFlag: false,
                    codeText: '重新发送验证码',
                })
            }

        }, 1000);
    },

    formSubmit: function (e) {
        const self = this;
        if (this.data.authorizeBtn) {
            this.dialog.showDialog()

            return false
        }
        let {
            mobilePhone,
            vCodeValue,
            countryArray,
            countryIndex
        } = this.data;
        let countryCode = countryArray[countryIndex].countrycode
        let param = {}

        param = {
            mobile_phone: mobilePhone,
            country_code: countryCode,
            vcode: vCodeValue,
            login_type: 0
        }

        let options = {
            url: requestApi.loginUrl,
            method: 'POST',
            data: param,
        }

        if (this.data.requestFlag) return false

        this.setData({
            requestFlag: true,
        })

        wx.showLoading({
            title: '登录中...'
        });

        wx.login({
            success(res) {
                console.log(res.code);
                app.request({
                    url: requestApi.getKey,
                    method: 'POST',
                    login: false,
                    data: {
                        js_code: res.code
                    },
                }, (w_code) => {
                    app.request(
                        options,
                        (data) => {
                            wx.hideLoading()

                            var userinfo = wx.getStorageSync('userinfo') || {}

                            userinfo = extend(true, {}, userinfo, {
                                'openid': w_code.original.data.openid
                            })
                            wx.setStorageSync('userinfo', userinfo);

                            if (app.data.newUserPop && app.data.newUserPop.coupon_no) {
                                self.receiveCoupon();
                            } else {
                                wx.showToast({
                                    title: '登录成功！',
                                    duration: 1000,
                                })

                                wx.navigateBack({
                                    delta: 2
                                })
                            }
                        },
                        (error) => {
                            wx.hideLoading()
                            wx.showModal({
                                title: '提示',
                                showCancel: false,
                                content: error,
                            })
                        }, () => {
                            self.setData({
                                requestFlag: false,
                            })
                        })
                }, (error) => {
                    wx.showModal({
                        title: '提示',
                        showCancel: false,
                        content: error,
                    })
                })
            }
        })
    },
    // 新手优惠，一键领取优惠券
    receiveCoupon() {
        const {
            channel
        } = this.data;

        app.request({
            url: requestApi.receiveCoupon,
            data: {
                is_new_ver: true,
                coupon_no: app.data.newUserPop.coupon_no,
                channel: channel
            },
        }, (data) => {
            wx.showToast({
                title: '登录成功，开启购物之旅，好礼将在1-2分钟内发放至您的优惠券账户',
                duration: 1000,
            })
        }, (error) => {
            // 
        }, () => {
            wx.navigateBack({
                delta: 2
            })
        })
    },
})